Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 2x 2x 5x 5x 5x 5x 5x 5x 5x 7x 1x 1x 4x 4x 4x 4x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 4x 4x 4x 4x 4x 1x 1x 1x 1x 2x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 1x 1x 3x 3x 3x 3x 3x 4x 1x 1x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | export const dynamic = "force-dynamic";
import { NextRequest, NextResponse } from 'next/server';
import { } from "next-auth";
import { prisma } from "@/lib/prisma";
import { logger } from "@/lib/logging";
import { z } from "zod";
import { pricingEngine } from "@/lib/ecommerce";
import {
withAdmin,
withErrorHandling,
successResponse,
ApiError,
ApiSuccessResponse,
ApiErrorResponse } from "@/lib/api";
import { RouteContext } from "@/lib/api/middleware";
const LOG_CATEGORY = "ADMIN_PRICING_API";
// Validation schema for updates
const pricingConditionSchema = z.object({
field: z.string(),
operator: z.enum([
"equals",
"not_equals",
"greater_than",
"less_than",
"greater_than_or_equal",
"less_than_or_equal",
"in",
"not_in",
"between",
]),
value: z.union([
z.string(),
z.number(),
z.array(z.string()),
z.array(z.number()),
]) });
const updatePricingRuleSchema = z.object({
name: z.string().min(1).max(100).optional(),
description: z.string().max(500).optional().nullable(),
type: z.enum([
"VOLUME_DISCOUNT",
"TIME_BASED",
"INVENTORY_BASED",
"SEGMENT_BASED",
"CLEARANCE",
"FIRST_TIME_BUYER",
"BUNDLE_DISCOUNT",
"COMPETITIVE",
"SEASONAL",
"DEMAND_BASED",
]).optional(),
discountType: z.enum(["PERCENTAGE", "FIXED_AMOUNT"]).optional(),
discountValue: z.number().min(0).optional(),
conditions: z.array(pricingConditionSchema).optional(),
priority: z.number().int().min(0).max(100).optional(),
stackable: z.boolean().optional(),
minimumQuantity: z.number().int().min(1).optional().nullable(),
minimumPurchase: z.number().min(0).optional().nullable(),
maximumDiscount: z.number().min(0).optional().nullable(),
startDate: z.string().datetime().optional().nullable(),
endDate: z.string().datetime().optional().nullable(),
isActive: z.boolean().optional(),
targetType: z.enum([
"ALL_PRODUCTS",
"SPECIFIC_PRODUCTS",
"SPECIFIC_CATEGORIES",
"CART_TOTAL",
]).optional(),
targetProductIds: z.array(z.number()).optional(),
targetCategoryIds: z.array(z.number()).optional(),
targetSegmentIds: z.array(z.number()).optional(),
abTestEnabled: z.boolean().optional(),
abTestVariant: z.string().max(50).optional().nullable(),
abTestPercent: z.number().int().min(0).max(100).optional().nullable() });
interface RouteParams {
params: Promise<{ id: string }>;
}
/**
* GET /api/admin/pricing/[id]
* Get a single pricing rule
*/
async function handleGet(_request: NextRequest,
context: RouteContext | undefined): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
const { id } = await (context as RouteParams).params;
const ruleId = parseInt(id);
if (isNaN(ruleId)) {
throw ApiError.badRequest("Invalid rule ID");
}
const rule = await prisma.pricingRule.findUnique({
where: { id: ruleId },
include: {
targetProducts: { select: { productId: true } },
targetCategories: { select: { categoryId: true } },
targetSegments: { select: { segmentId: true } },
_count: {
select: { applications: true } } } });
if (!rule) {
throw ApiError.notFound("Pricing rule");
}
return successResponse({
id: rule.id,
name: rule.name,
description: rule.description,
type: rule.type,
discountType: rule.discountType,
discountValue: rule.discountValue,
conditions: rule.conditions,
priority: rule.priority,
stackable: rule.stackable,
minimumQuantity: rule.minimumQuantity,
minimumPurchase: rule.minimumPurchase,
maximumDiscount: rule.maximumDiscount,
startDate: rule.startDate,
endDate: rule.endDate,
isActive: rule.isActive,
targetType: rule.targetType,
targetProductIds: rule.targetProducts.map((tp) => tp.productId),
targetCategoryIds: rule.targetCategories.map((tc) => tc.categoryId),
targetSegmentIds: rule.targetSegments.map((ts) => ts.segmentId),
abTestEnabled: rule.abTestEnabled,
abTestVariant: rule.abTestVariant,
abTestPercent: rule.abTestPercent,
applicationCount: rule._count.applications,
totalDiscounted: rule.totalDiscounted,
createdAt: rule.createdAt,
updatedAt: rule.updatedAt });
}
/**
* PUT /api/admin/pricing/[id]
* Update a pricing rule
*/
async function handlePut(request: NextRequest,
context: RouteContext | undefined): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
const { id } = await (context as RouteParams).params;
const ruleId = parseInt(id);
if (isNaN(ruleId)) {
throw ApiError.badRequest("Invalid rule ID");
}
const body = await request.json();
// Validate input
const validationResult = updatePricingRuleSchema.safeParse(body);
if (!validationResult.success) {
throw ApiError.validation("Validation failed", validationResult.error.issues);
}
const validatedData = validationResult.data;
// Check if rule exists
const existingRule = await prisma.pricingRule.findUnique({
where: { id: ruleId } });
if (!existingRule) {
throw ApiError.notFound("Pricing rule");
}
// Build update data
const updateData: Record<string, unknown> = {};
if (validatedData.name !== undefined) updateData.name = validatedData.name;
if (validatedData.description !== undefined) updateData.description = validatedData.description;
if (validatedData.type !== undefined) updateData.type = validatedData.type;
if (validatedData.discountType !== undefined) updateData.discountType = validatedData.discountType;
if (validatedData.discountValue !== undefined) updateData.discountValue = validatedData.discountValue;
if (validatedData.conditions !== undefined) updateData.conditions = validatedData.conditions;
if (validatedData.priority !== undefined) updateData.priority = validatedData.priority;
if (validatedData.stackable !== undefined) updateData.stackable = validatedData.stackable;
if (validatedData.minimumQuantity !== undefined) updateData.minimumQuantity = validatedData.minimumQuantity;
if (validatedData.minimumPurchase !== undefined) updateData.minimumPurchase = validatedData.minimumPurchase;
if (validatedData.maximumDiscount !== undefined) updateData.maximumDiscount = validatedData.maximumDiscount;
if (validatedData.startDate !== undefined) {
updateData.startDate = validatedData.startDate ? new Date(validatedData.startDate) : null;
}
if (validatedData.endDate !== undefined) {
updateData.endDate = validatedData.endDate ? new Date(validatedData.endDate) : null;
}
if (validatedData.isActive !== undefined) updateData.isActive = validatedData.isActive;
if (validatedData.targetType !== undefined) updateData.targetType = validatedData.targetType;
if (validatedData.abTestEnabled !== undefined) updateData.abTestEnabled = validatedData.abTestEnabled;
if (validatedData.abTestVariant !== undefined) updateData.abTestVariant = validatedData.abTestVariant;
if (validatedData.abTestPercent !== undefined) updateData.abTestPercent = validatedData.abTestPercent;
// Update rule and relations in a transaction
const rule = await prisma.$transaction(async (tx) => {
// Update target products if provided
if (validatedData.targetProductIds !== undefined) {
await tx.pricingRuleProduct.deleteMany({ where: { pricingRuleId: ruleId } });
if (validatedData.targetProductIds.length > 0) {
await tx.pricingRuleProduct.createMany({
data: validatedData.targetProductIds.map((productId) => ({
pricingRuleId: ruleId,
productId })) });
}
}
// Update target categories if provided
if (validatedData.targetCategoryIds !== undefined) {
await tx.pricingRuleCategory.deleteMany({ where: { pricingRuleId: ruleId } });
if (validatedData.targetCategoryIds.length > 0) {
await tx.pricingRuleCategory.createMany({
data: validatedData.targetCategoryIds.map((categoryId) => ({
pricingRuleId: ruleId,
categoryId })) });
}
}
// Update target segments if provided
if (validatedData.targetSegmentIds !== undefined) {
await tx.pricingRuleSegment.deleteMany({ where: { pricingRuleId: ruleId } });
if (validatedData.targetSegmentIds.length > 0) {
await tx.pricingRuleSegment.createMany({
data: validatedData.targetSegmentIds.map((segmentId) => ({
pricingRuleId: ruleId,
segmentId })) });
}
}
// Update the rule itself
return tx.pricingRule.update({
where: { id: ruleId },
data: updateData,
include: {
targetProducts: { select: { productId: true } },
targetCategories: { select: { categoryId: true } },
targetSegments: { select: { segmentId: true } } } });
});
// Clear pricing engine cache
pricingEngine.clearCache();
logger.info("Pricing rule updated", { category: LOG_CATEGORY, ruleId: rule.id, name: rule.name });
return successResponse({
id: rule.id,
name: rule.name,
description: rule.description,
type: rule.type,
discountType: rule.discountType,
discountValue: rule.discountValue,
conditions: rule.conditions,
priority: rule.priority,
stackable: rule.stackable,
minimumQuantity: rule.minimumQuantity,
minimumPurchase: rule.minimumPurchase,
maximumDiscount: rule.maximumDiscount,
startDate: rule.startDate,
endDate: rule.endDate,
isActive: rule.isActive,
targetType: rule.targetType,
targetProductIds: rule.targetProducts.map((tp) => tp.productId),
targetCategoryIds: rule.targetCategories.map((tc) => tc.categoryId),
targetSegmentIds: rule.targetSegments.map((ts) => ts.segmentId),
abTestEnabled: rule.abTestEnabled,
abTestVariant: rule.abTestVariant,
abTestPercent: rule.abTestPercent,
createdAt: rule.createdAt,
updatedAt: rule.updatedAt });
}
/**
* DELETE /api/admin/pricing/[id]
* Delete a pricing rule
*/
async function handleDelete(_request: NextRequest,
context: RouteContext | undefined): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
const { id } = await (context as RouteParams).params;
const ruleId = parseInt(id);
if (isNaN(ruleId)) {
throw ApiError.badRequest("Invalid rule ID");
}
// Check if rule exists
const existingRule = await prisma.pricingRule.findUnique({
where: { id: ruleId } });
if (!existingRule) {
throw ApiError.notFound("Pricing rule");
}
// Delete the rule (cascade will handle relations)
await prisma.pricingRule.delete({
where: { id: ruleId } });
// Clear pricing engine cache
pricingEngine.clearCache();
logger.info("Pricing rule deleted", { category: LOG_CATEGORY, ruleId });
return successResponse({ message: "Pricing rule deleted successfully" });
}
export const GET = withErrorHandling(withAdmin(handleGet));
export const PUT = withErrorHandling(withAdmin(handlePut));
export const DELETE = withErrorHandling(withAdmin(handleDelete));
|